import React, { Component } from 'react';
import { Http } from 'brc-util';
import StaticSelect from '../static-select';

const Option = StaticSelect.Option;

class Select extends Component {
  constructor() {
    super();
    this.state = {
      remoteData: null,
    }
    this.getRemoteData = this.getRemoteData.bind(this);
  }
  getRemoteData() {
    const { dataUrl } = this.props;
    Http.get(dataUrl)
      .then(res => {
        this.setState({
          remoteData: res.data,
        });
      }).catch(e => {
        console.log(e);
      });
  }
  renderDefaultOption() {
    const { defaultText, defaultValue, data } = this.props;
    const { remoteData } = this.state;
    if (data) {
      return data.map(item => <Option key={item.value} value={item.value} title={item.text}>{item.text}</Option>);
    }
    if (remoteData) {
      return remoteData.map(item => <Option key={item.value} value={item.value} title={item.text}>{item.text}</Option>);
    }
    return <Option value={defaultValue} title={defaultText}>{defaultText}</Option>;
  }
  render() {
    const { data, ...rest } = this.props;
    return (
      <StaticSelect
        {...rest}
        onFocus={() => {
          if (!data) this.getRemoteData();
        }}
      >
        {this.renderDefaultOption()}
      </StaticSelect>
    );
  }
}

export default Select;
